package com.crb.crm.manage.message.common;

import com.crb.crm.manage.dao.biz.MessageSendRecordMapper;
import com.crb.crm.manage.pojo.biz.MessageSendRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * Package: com.gulimall.thrid.party.msg
 * Description：發消息策略
 * Author: huangjian
 * Date:  2020/6/18 14:48
 * Modified By:
 */
@Slf4j
public abstract class SMGSender {

    @Autowired
    protected MessageCtxConfig messageCtxConfig;
    @Resource
    private MessageSendRecordMapper messageSendRecordMapper;

    private SAGTemplate template;

    public SAGTemplate getTemplate() {
        return template;
    }

    /**
     * 檢查渠道是否可用
     *
     * @return
     */
    protected void channelIsActive() {
        Assert.isTrue(messageCtxConfig.config(support()).getActive(),"渠道"+support()+"未啟動，請檢查");
    }

    public void setTemplate(SAGTemplate template) {
        this.template = template;
    }
    public void sendMessage(Map<String, String> param, String reviver){
        MessageSendRecord record=new MessageSendRecord();
        try {
            channelIsActive();
            sendMsg(this.template,support().getSignature(),param,reviver);
            record.setSuccess(true);
            record.setChannel(support().getPartnerName());
            record.setContent(content());
            record.setReceiver(reviver);
            record.setIsDel(false);
            record.setName(this.template.getDesc());
            record.setInsertTime(new Date());
        }catch (Exception e){
            e.printStackTrace();
            record.setSuccess(false);
            record.setExceptionContext(e.getMessage());
        }
        messageSendRecordMapper.insertSelective(record);
    }
    public abstract SMGChannel support();
    public abstract String content();
    protected abstract void sendMsg(SAGTemplate templateId,String signature,Map<String, String> param, String reviver);

}
